package guo.controller;

import org.bytedeco.javacpp.opencv_core;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.FrameGrabber;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
public class VideoFrameExtractor {

    public static void extractFrames(MultipartFile videoFile, String framefile) throws IOException, FrameGrabber.Exception {
        long start = System.currentTimeMillis();
        File targetFile = new File("E:/video/111.mp4");
        FileCopyUtils.copy(videoFile.getBytes(), targetFile);

        FFmpegFrameGrabber ff = new FFmpegFrameGrabber(targetFile);
        ff.start();
        int lenght = ff.getLengthInFrames();
        int i = 0;
        Frame f = null;
        while (i < lenght) {
            // 过滤前5帧，避免出现全黑的图片，依自己情况而定
            f = ff.grabFrame();
//            if ((i > 5) && (f.image != null)) {
//                break;
//            }
            if (f.image == null){
                System.out.println("第 "+ i +" 帧为空");
                i++;
                continue;
            }

            opencv_core.IplImage img = f.image;
            int owidth = img.width();
            int oheight = img.height();
            // 对截取的帧进行等比例缩放
            int width = 800;
            int height = (int) (((double) width / owidth) * oheight);
            BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
            bi.getGraphics().drawImage(f.image.getBufferedImage().getScaledInstance(width, height, Image.SCALE_SMOOTH),
                    0, 0, null);
            ImageIO.write(bi, "jpg", new File(framefile+ i + ".jpg"));
            i++;
        }

        //ff.flush();
        ff.stop();
        System.out.println(System.currentTimeMillis() - start);
    }

    @PostMapping("/video/file")
    public String videoToString(MultipartFile videoFile) {
//        MultipartFile videoFile = null; // 从请求中获取上传的视频文件
        String outputDirectory = "E:/video/img/"; // 设置输出目录

        try {
            VideoFrameExtractor.extractFrames(videoFile, outputDirectory);
            System.out.println("帧提取完成");
        } catch (Exception e) {
            // 处理异常
            throw new RuntimeException("出错了");
        }
        return "ok";
    }
}